package com.hnhegui.backend.merchant.service;

import com.hnhegui.backend.entity.PageResult;
import com.hnhegui.backend.exception.BusinessException;
import com.hnhegui.backend.merchant.dto.request.DeductStockRequestDTO;
import com.hnhegui.backend.merchant.dto.request.FreezeStockRequestDTO;
import com.hnhegui.backend.merchant.dto.request.ProductPageRequestDTO;
import com.hnhegui.backend.merchant.dto.request.UnfreezeStockRequestDTO;
import com.hnhegui.backend.merchant.dto.response.ProductDetailsResponseDTO;
import com.hnhegui.backend.merchant.entity.Product;
import com.hnhegui.backend.merchant.mapper.ProductMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public PageResult<ProductDetailsResponseDTO> getProductList(ProductPageRequestDTO request) {
        int offset = (request.getPage() - 1) * request.getPageSize();

        // 只查询在售商品
        Integer status = 1;

        // 查询商品列表
        List<Product> products = productMapper.findList(request.getCategory(), request.getKeyword(), status,
                request.getSortBy(), request.getSortOrder(), offset, request.getPageSize());

        // 统计总数
        long total = productMapper.count(request.getCategory(), request.getKeyword(), status);

        // 转换为DTO
        List<ProductDetailsResponseDTO> items = products.stream().map(product -> {
            ProductDetailsResponseDTO item = new ProductDetailsResponseDTO();
            item.setProductId(product.getProductId().toString());
            item.setName(product.getProductName());
            item.setPrice(product.getPrice());
            item.setStock(product.getStock());
            item.setImageUrl(product.getImageUrl());
            item.setCategory(product.getCategory());
            return item;
        }).collect(Collectors.toList());

        return new PageResult<>(total, items);
    }


    /**
     * 获取商品详情
     */
    public ProductDetailsResponseDTO getProductDetail(Long productId) {
        Product product = productMapper.findById(productId);

        if (product == null) {
            throw new BusinessException(40401, "商品不存在");
        }

        ProductDetailsResponseDTO response = new ProductDetailsResponseDTO();
        response.setProductId(product.getProductId().toString());
        response.setName(product.getProductName());
        response.setDescription(product.getDescription());
        response.setPrice(product.getPrice());
        response.setStock(product.getStock());
        response.setImages(product.getImageList());
        response.setCategory(product.getCategory());
        response.setAttributes(product.getAttributeMap());
        response.setType(product.getProductType().name());
        response.setStatus(product.getStatus());
        return response;
    }

    /**
     * 验证商品并获取详情
     */
    public Product validateAndGetProduct(Long productId, Integer quantity) {
        Product product = productMapper.selectForUpdate(productId);

        if (product == null) {
            throw new BusinessException(40401, "商品不存在");
        }

        if (product.getStatus() == 0) {
            throw new BusinessException(40001, "商品已下架");
        }

        if (product.getStock() < quantity) {
            throw new BusinessException(40002, "库存不足");
        }

        return product;
    }

    /**
     * 冻结库存
     * @param request 请求入参
     */
    public Boolean freezeStock(FreezeStockRequestDTO request) {
        //这里需要加一个商品的锁，防止商品超卖
        RLock lock = redissonClient.getLock("product:" + request.getProductId());
        if (!lock.tryLock()) {
            throw new BusinessException(50001, "冻结库存操作失败");
        }
        String redisKey = String.format("product:stock:%d", request.getProductId());
        try {
            //获取商品信息
            validateAndGetProduct(request.getProductId(), request.getFreezeStock());
            redisTemplate.opsForHash().put(redisKey, request.getOrderId(), request.getFreezeStock());
            //扣除商品库存操作
            int updated = productMapper.decreaseStock(request.getProductId(), request.getFreezeStock());
            if (updated == 0) {
                throw new BusinessException(50001, "商品冻结失败");
            }
            return true;
        } catch (Exception e) {
            //删除冻结库存
            redisTemplate.opsForHash().delete(redisKey, request.getFreezeStock());
            throw new BusinessException(50001, "商品冻结失败");
        }
        finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread())
                lock.unlock();
        }
    }

    /**
     * 库存解冻
     * @param request   请求入参
     */
    public void unfreezeStock(UnfreezeStockRequestDTO request) {
        //解冻不需要加锁
        //获取缓存数据
        String redisKey = String.format("product:stock:%d", request.getProductId());
        Object o = redisTemplate.opsForHash().get(redisKey, request.getOrderId());
        if (Objects.isNull(o)) {
            //保证幂等，这里直接返回
            return;
        }
        Integer freezeStock = Integer.parseInt(o.toString());
        //删除缓存
        Long delete = redisTemplate.opsForHash().delete(redisKey, request.getOrderId());
        if (delete > 0) {
            productMapper.increaseStock(request.getProductId(), freezeStock);
        }
    }

    public void deductStock(DeductStockRequestDTO request) {
        String redisKey = String.format("product:stock:%d", request.getProductId());
        redisTemplate.opsForHash().delete(redisKey, request.getOrderId());
    }
}
